package com.helen.ui.help;

import android.content.Intent;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.coorchice.library.SuperTextView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.helen.adapter.GridImageAdapter;
import com.helen.db.UserHelper;
import com.helen.entity.AddressListEntity;
import com.helen.entity.UpLoadPicEntity;
import com.helen.global.Constants;
import com.helen.shopping.R;
import com.helen.ui.BaseActivity;
import com.helen.ui.address.AddressListActivity;
import com.helen.ui.helpordel.HelpOrderActivity;
import com.helen.utils.MyLog;
import com.helen.utils.PhoneUtils;
import com.helen.utils.tiputils.MToast;
import com.helen.widget.ActionSheetDialog;
import com.helen.widget.FullyGridLayoutManager;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;
import com.zhouyou.http.model.HttpParams;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by yang on 2018/5/8.
 */

public class HelpActivity extends BaseActivity {
    private static final int LOCATION = 0x11;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_detail_address)
    TextView tvDetailAddress;
    @BindView(R.id.ll_address)
    LinearLayout llAddress;
    @BindView(R.id.et_title)
    EditText etTitle;
    @BindView(R.id.et_good)
    EditText etGood;
    @BindView(R.id.et_wx)
    EditText etWx;
    @BindView(R.id.et_num)
    EditText etNum;
    @BindView(R.id.et_detail_content)
    EditText etDetailContent;
    @BindView(R.id.recycler)
    RecyclerView recyclerView;
    @BindView(R.id.tv_release)
    SuperTextView tvRelease;
    private AddressListEntity addressListEntity;
    private List<LocalMedia> selectList = new ArrayList<>();
    private GridImageAdapter adapter;
    private int maxSelectNum = 9;
    private List<UpLoadPicEntity> picList = new ArrayList<>();

    @Override
    protected int attachLayoutRes() {

        return R.layout.activity_help;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        String[] homeClassificationName = getResources().getStringArray(R.array.home_classification);
        getToolbarTitle().setText(homeClassificationName[7]);
        FullyGridLayoutManager manager = new FullyGridLayoutManager(HelpActivity.this, 4, GridLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(manager);
        adapter = new GridImageAdapter(HelpActivity.this, onAddPicClickListener);
        adapter.setList(selectList);
        recyclerView.setAdapter(adapter);
        adapter.setSelectMax(maxSelectNum);
        adapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                if (selectList.size() > 0) {
                    LocalMedia media = selectList.get(position);
                    String pictureType = media.getPictureType();
                    int mediaType = PictureMimeType.pictureToVideo(pictureType);
                    switch (mediaType) {
                        case 1:
//                             预览图片 可自定长按保存路径
//                            PictureSelector.create(UserDonationActivity.this).themeStyle(R.style.picture_QQ_style).externalPicturePreview(position, "/custom_file", selectList);
                            PictureSelector.create(HelpActivity.this).themeStyle(R.style.picture_QQ_style).openExternalPreview(position, selectList);
                            break;
//
                    }
                }
            }
        });
    }

    @Override
    protected void updateViews() {

    }


    @OnClick({R.id.ll_address, R.id.tv_release})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_address:
                Intent ti = new Intent(this, AddressListActivity.class);
                ti.putExtra("backModel", true);
                startActivityForResult(ti, LOCATION);
                break;
            case R.id.tv_release:

                String title, goodstype, WX, count, content;
                title = etTitle.getText().toString().trim();
                goodstype = etGood.getText().toString().trim();
                WX = etWx.getText().toString().trim();
                count = etNum.getText().toString().trim();
                content = etDetailContent.getText().toString().trim();
                if (addressListEntity == null) {
                    MToast.makeTextShort(this, "请选择地址").show();
                    return;
                }
                if (TextUtils.isEmpty(title)) {
                    MToast.makeTextShort(this, "请输入求助标题").show();
                    etTitle.requestFocus();
                    return;
                }

                if (TextUtils.isEmpty(goodstype)) {
                    MToast.makeTextShort(this, "请输入求助物品").show();
                    etGood.requestFocus();
                    return;
                }
                if (TextUtils.isEmpty(count)) {
                    MToast.makeTextShort(this, "请输入数量").show();
                    etNum.requestFocus();
                    return;
                }

                if (selectList == null || selectList.size() == 0) {
                    MToast.makeTextShort(this, "请输入请上传照片").show();
                    return;
                }
                updLoadPic(title, goodstype, WX, count, content);
                break;
        }
    }


    //上传照片
    private void updLoadPic(final String title, final String goodstype, final String WX, final String count, final String content) {
        mMProgressDialog.show();
        String url = Constants.APP_API_BASE + Constants.API_JSONAPI_UPDATEIMG;
        RequestParams params = new RequestParams(url);
        params.setMultipart(true);

        try {
            if (selectList != null && selectList.size() > 0) {
                for (int i = 0; i < selectList.size(); i++) {
                    params.addBodyParameter("file" + (i + 1), new FileInputStream(new File(selectList.get(i).getPath())), "img/jpg", "pic" + i + ".jpg");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                MyLog.e("yang", "上传图片成功==" + result);
                String data = PhoneUtils.checkResponseFlag2(HelpActivity.this, result, TAG);
                String imgUrls = "";
                if (data != null) {
                    picList = new Gson().fromJson(data, new TypeToken<List<UpLoadPicEntity>>() {
                    }.getType());

                    for (int i = 0; i < picList.size(); i++) {
                        imgUrls += (i == 0 ? "" : ",") + picList.get(i).getRelativeurl();
                    }
                    helpApi(title, goodstype, WX, count, content, imgUrls);

                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                MyLog.e("yang", "上传图片失败=" + ex.toString());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                mMProgressDialog.dismiss();
            }
        });


    }


    private void helpApi(String title, String goodstype, String WX, String count, String content, String imgurls) {
        mMProgressDialog.show();
        HttpParams params = new HttpParams();
        params.put("userid", UserHelper.getInstance().getloginEntity(HelpActivity.this).getId() + "");
        params.put("addressid", addressListEntity.getId() + "");
        params.put("title", title);
        params.put("goodstype", goodstype);
        params.put("WX", WX);
        params.put("count", count);
        params.put("content", content);
        params.put("imgurls", imgurls);
        EasyHttp.post(Constants.API_JSONAPI_HELP)
                .params(params)
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        mMProgressDialog.dismiss();
                    }

                    @Override
                    public void onError(ApiException e) {
                        MyLog.e("yang", "需要帮助失败==" + e.toString());
                        MToast.makeTextLong(HelpActivity.this, getString(R.string.service_error)).show();
                    }

                    @Override
                    public void onSuccess(String result) {
                        String data = PhoneUtils.checkResponseFlag(HelpActivity.this, result, TAG);
                        if (data != null) {
                            Intent ti = new Intent(HelpActivity.this, HelpOrderActivity.class);
                            ti.putExtra("currentId", 1);
                            startActivity(ti);
                            MToast.makeTextLong(HelpActivity.this, "发布成功,等待审核").show();
                            finish();
                        }
                    }
                });

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case LOCATION:
                    if (data != null) {
                        addressListEntity = (AddressListEntity) data.getSerializableExtra("addressListEntity");
                        tvName.setText("姓名: " + addressListEntity.getName());
                        tvPhone.setText(addressListEntity.getPhone());
                        tvDetailAddress.setText("详细地址: " + addressListEntity.getCity() + addressListEntity.getDetail());
                    }
                    break;
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的
                    adapter.setList(selectList);
                    adapter.notifyDataSetChanged();
                    break;

            }
        }
    }


    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick(final int type) {
            switch (type) {
                case 1:
                    new ActionSheetDialog(HelpActivity.this).builder()
                            .setCancelable(false)
                            .setCanceledOnTouchOutside(true)
                            .addSheetItem("拍照", ActionSheetDialog.SheetItemColor.ThemeColor,
                                    new ActionSheetDialog.OnSheetItemClickListener() {
                                        @Override
                                        public void onClick(int which) {
                                            PictureSelector.create(HelpActivity.this)
                                                    .openCamera(PictureMimeType.ofImage())// 单独拍照，也可录像或也可音频 看你传入的类型是图片or视频
                                                    .theme(R.style.picture_QQ_style)// 主题样式设置 具体参考 values/styles
                                                    .maxSelectNum(maxSelectNum)// 最大图片选择数量
                                                    .minSelectNum(1)// 最小选择数量
                                                    .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选
                                                    .previewImage(true)// 是否可预览图片
                                                    .previewVideo(false)// 是否可预览视频
                                                    .enablePreviewAudio(false) // 是否可播放音频
                                                    .isCamera(false)// 是否显示拍照按钮
                                                    .enableCrop(false)// 是否裁剪
                                                    .compress(false)// 是否压缩
                                                    .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                                                    .withAspectRatio(1, 1)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                                                    .hideBottomControls(false)// 是否显示uCrop工具栏，默认不显示
                                                    .isGif(false)// 是否显示gif图片
                                                    .freeStyleCropEnabled(false)// 裁剪框是否可拖拽
                                                    .circleDimmedLayer(false)// 是否圆形裁剪
                                                    .showCropFrame(false)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
                                                    .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false
                                                    .openClickSound(true)// 是否开启点击声音
                                                    .selectionMedia(selectList)// 是否传入已选图片
                                                    .previewEggs(false)//预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)
                                                    //.previewEggs(false)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)
                                                    //.cropCompressQuality(90)// 裁剪压缩质量 默认为100
                                                    .minimumCompressSize(100)// 小于100kb的图片不压缩
                                                    //.cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效
                                                    //.rotateEnabled() // 裁剪是否可旋转图片
                                                    //.scaleEnabled()// 裁剪是否可放大缩小图片
                                                    //.videoQuality()// 视频录制质量 0 or 1
                                                    //.videoSecond()////显示多少秒以内的视频or音频也可适用
                                                    .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
                                        }
                                    })
                            .addSheetItem("相册", ActionSheetDialog.SheetItemColor.ThemeColor,
                                    new ActionSheetDialog.OnSheetItemClickListener() {
                                        @Override
                                        public void onClick(int which) {
                                            // 进入相册 以下是例子：不需要的api可以不写
                                            PictureSelector.create(HelpActivity.this)
                                                    .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                                                    .theme(R.style.picture_QQ_style)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style
                                                    .maxSelectNum(maxSelectNum)// 最大图片选择数量
                                                    .minSelectNum(1)// 最小选择数量
                                                    .imageSpanCount(4)// 每行显示个数
                                                    .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选
                                                    .previewImage(true)// 是否可预览图片
                                                    .previewVideo(false)// 是否可预览视频
                                                    .enablePreviewAudio(false) // 是否可播放音频
                                                    .isCamera(false)// 是否显示拍照按钮
                                                    .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                                                    //.imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                                                    //.setOutputCameraPath("/CustomPath")// 自定义拍照保存路径
                                                    .enableCrop(false)// 是否裁剪
                                                    .compress(false)// 是否压缩
                                                    .synOrAsy(true)//同步true或异步false 压缩 默认同步
                                                    //.compressSavePath(getPath())//压缩图片保存地址
                                                    //.sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                                                    .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                                                    .withAspectRatio(1, 1)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                                                    .hideBottomControls(false)// 是否显示uCrop工具栏，默认不显示
                                                    .isGif(false)// 是否显示gif图片
                                                    .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                                                    .circleDimmedLayer(false)// 是否圆形裁剪
                                                    .showCropFrame(false)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
                                                    .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false
                                                    .openClickSound(true)// 是否开启点击声音
                                                    .selectionMedia(selectList)// 是否传入已选图片
                                                    //.isDragFrame(false)// 是否可拖动裁剪框(固定)
//                        .videoMaxSecond(15)
//                        .videoMinSecond(10)
                                                    //.previewEggs(false)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)
                                                    //.cropCompressQuality(90)// 裁剪压缩质量 默认100
                                                    .minimumCompressSize(100)// 小于100kb的图片不压缩
                                                    //.cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效
                                                    //.rotateEnabled(true) // 裁剪是否可旋转图片
                                                    //.scaleEnabled(true)// 裁剪是否可放大缩小图片
                                                    //.videoQuality()// 视频录制质量 0 or 1
                                                    //.videoSecond()//显示多少秒以内的视频or音频也可适用
                                                    //.recordVideoSecond()//录制视频秒数 默认60s
                                                    .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
                                        }
                                    }).show();
                    break;

            }


        }

    };
}
